//
//  RYChatViewController.m
//  SanYiTeaching
//
//  Created by ChenHao on 2019/8/1.
//  Copyright © 2019 SanYi. All rights reserved.
//

#import "RYChatViewController.h"
#import "RYChatVideoCell.h"
#import "RYVideoMessageContent.h"
#import "SimpleMessageCell.h"
#import "SimpleMessage.h"
#import "ChatInfoNavView.h"
#import "SYZXFDFuDaoDetailsView.h"

#import <MobileCoreServices/MobileCoreServices.h>
#import "BLImagePickerViewController.h"
#import "BLImageClipingViewController.h"
#import "SYWordViewController.h"
#import "SYPPTViewController.h"

#import "WMPhotoBrowser.h"

#import "XFCameraController.h"
#import "SYSendVideoViewController.h"

#import "SYPlayerViewController.h"

//#import "SYScreenViewController.h"//录屏

#import "ResourceViewController.h"

#import "WMVideoMessage.h"
#import "WMVideoMessageCell.h"

#import "SYBaiBanFuDaoViewController.h"

#import "WMPPTMessageCell.h"
#import "WMPPTMessage.h"
#import "WMWordMessage.h"
#import "WMWordMessageCell.h"

#import "WMHttpMessage.h"
#import "WMHttpMessageCell.h"


#import "WMExcelMessage.h"
#import "WMExcelMessageCell.h"
#import "WMImageMessage.h"
#import "WMImageMessageCell.h"
#import "SYPPTViewController.h"


@interface RYChatViewController ()<RCMessageCellDelegate,RCChatSessionInputBarControlDelegate,RCChatSessionInputBarControlDataSource,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIDocumentPickerDelegate,TZImagePickerControllerDelegate>
{
    ChatInfoNavView *InfoV;
    WMPhotoBrowser *browser;
    UIButton *leftBtn;
}
@property (nonatomic ,strong)  UIImagePickerController *picker;
@property (nonatomic ,strong) SYBaiBanFuDaoViewController *interactionVC;
@end

@implementation RYChatViewController
- (instancetype)init
{
    self = [super init];
    if (self) {
        self.hidesBottomBarWhenPushed = YES;
    }
    return self;
}
-(void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    
}

- (void)dealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(faSongLuPing:) name:@"faSongLuPing" object:nil];
    
    [self.chatSessionInputBarControl.pluginBoardView removeItemWithTag:1104];
    [self.chatSessionInputBarControl.pluginBoardView removeItemWithTag:1003];
    //在功能面板上插入一个Item，用来发送视频，并标记tag，方便区分
    [self.chatSessionInputBarControl.pluginBoardView insertItemWithImage:[UIImage imageNamed:@"chat_sendVideo"]
                                        title:@"发送视频"
                                          tag:201];
    //在功能面板上插入一个Item，用来发送视频，并标记tag，方便区分
    [self.chatSessionInputBarControl.pluginBoardView insertItemWithImage:[UIImage imageNamed:@"chat_sendField"]
                                        title:@"发送文件"
                                          tag:202];
    
    [self.chatSessionInputBarControl.pluginBoardView insertItemWithImage:[UIImage imageNamed:@"chat_sendSmallVideo"]
                                        title:@"小视频"
                                          tag:204];
    
    [self.chatSessionInputBarControl.pluginBoardView insertItemWithImage:[UIImage imageNamed:@"chat_sendLuPing"]
                                        title:@"录屏辅导"
                                          tag:205];
    
    [self.chatSessionInputBarControl.pluginBoardView insertItemWithImage:[UIImage imageNamed:@"chat_sendField"]
                                        title:@"选择资源"
                                          tag:206];
    
    
    self.conversationMessageCollectionView.backgroundColor = [UIColor whiteColor];
    
    [[RCIM sharedRCIM] registerMessageType:[SimpleMessage class]];
    [[RCIM sharedRCIM] registerMessageType:[WMVideoMessage class]];
    [[RCIM sharedRCIM] registerMessageType:[WMPPTMessage class]];
    [[RCIM sharedRCIM] registerMessageType:[WMWordMessage class]];
    [[RCIM sharedRCIM] registerMessageType:[WMExcelMessage class]];
    [[RCIM sharedRCIM] registerMessageType:[WMImageMessage class]];
    [[RCIM sharedRCIM] registerMessageType:[WMHttpMessage class]];




    ///注册自定义视频消息Cell
    [self registerClass:[RYChatVideoCell class] forCellWithReuseIdentifier:@"RYChatVideoCell"];
    [self registerClass:[SimpleMessageCell class] forCellWithReuseIdentifier:@"SimpleMessageCell"];
    [self registerClass:[WMVideoMessageCell class] forCellWithReuseIdentifier:@"WMVideoMessageCell"];
    [self registerClass:[WMPPTMessageCell class] forCellWithReuseIdentifier:@"WMPPTMessageCell"];
    [self registerClass:[WMWordMessageCell class] forCellWithReuseIdentifier:@"WMWordMessageCell"];
    [self registerClass:[WMExcelMessageCell class] forCellWithReuseIdentifier:@"WMExcelMessageCell"];
    [self registerClass:[WMImageMessageCell class] forCellWithReuseIdentifier:@"WMImageMessageCell"];
    
    [self registerClass:[WMHttpMessageCell class] forCellWithReuseIdentifier:@"WMHttpMessageCell"];


    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 65)];
    view.backgroundColor = [UIColor colorWithHexString:@"#E4E4E4"];
    [self.view addSubview:view];
    
    UIView *InfoView = [[UIView alloc]initWithFrame:CGRectMake(0, 20, view.bounds.size.width, 44)];
    InfoView.backgroundColor = [UIColor whiteColor];
    [view addSubview:InfoView];
    
    __weak typeof(self) weakSelf = self;
    
    if ([self.IsFrom isEqualToString:@"1"]) {
        InfoV = [ChatInfoNavView xibCreatInfoNavView];
        InfoV.frame = CGRectMake(0, 0, InfoView.bounds.size.width, InfoView.bounds.size.height);
        InfoV.classTypeLable.text = self.typeName;
        InfoV.classNameLable.text = [NSString stringWithFormat:@"班级名称：%@",self.className];
        
        InfoV.backButtonClick = ^{
            if (weakSelf.refrshListViewInfo) {
                weakSelf.refrshListViewInfo();
            }

            [weakSelf.view removeFromSuperview];
        };
        
        InfoV.AllInfoLookClick = ^{
            SYZXFDFuDaoDetailsView *detailsView = [[NSBundle mainBundle] loadNibNamed:@"SYZXFDFuDaoDetailsView" owner:nil options:nil].firstObject;
            [detailsView requestDataClassId:weakSelf.classId];
            [weakSelf.view addSubview:detailsView];
            [detailsView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(@0);
                make.right.equalTo(@0);
                make.top.equalTo(@0);
                make.bottom.equalTo(@0);
            }];

        };
        
        InfoV.endTheChatBtnClick = ^{
//            self.classStyle = @"1";
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"确定结束" message:@"" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            UIAlertAction *confirm = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
                [weakSelf changeChatGroupStyleWithStyle:@"1"];

            }];
            
            [alert addAction:cancel];
            [alert addAction:confirm];
            [self presentViewController:alert animated:YES completion:nil];

        };
        [InfoView addSubview:InfoV];
        
        if ([self.classStyle isEqualToString:@"0"]) {
            [self changeChatGroupStyleWithStyle:@"0"];
        }else{
            self.chatSessionInputBarControl.hidden = YES;
            self->InfoV.endBtn.backgroundColor = [UIColor whiteColor];
            [self->InfoV.endBtn setTitle:@"已结束" forState:UIControlStateNormal];
            InfoV.endBtn.enabled = NO;
            [self->InfoV.endBtn setTitleColor:[UIColor colorWithHexString:@"#20B097"] forState:UIControlStateNormal];
        }
        
    }else{
        if ([self.IsFrom isEqualToString:@"detail"]) {
            UIButton *backbtn = [[UIButton alloc]init];
            backbtn.center = CGPointMake(30, InfoView.center.y-20);
            backbtn.bounds = CGRectMake(0, 0, 60, 40);
            [backbtn setTitle:@"返回" forState:UIControlStateNormal];
            [backbtn setImage:[UIImage imageNamed:@"back_color"] forState:UIControlStateNormal];
            [backbtn setTitleColor:[UIColor colorWithHexString:@"#20B097"] forState:UIControlStateNormal];
            [backbtn addTarget:self action:@selector(detailInfoVcBackClick) forControlEvents:UIControlEventTouchUpInside];
            backbtn.titleLabel.font = [UIFont systemFontOfSize:13];
            [InfoView addSubview:backbtn];

        }
        UILabel *TitleLable = [[UILabel alloc]init];
        TitleLable.center = CGPointMake(InfoView.center.x-160, InfoView.center.y-20);
        TitleLable.bounds = CGRectMake(0, 0, 200, 20);
        TitleLable.text = self.UserName;
        TitleLable.font = [UIFont systemFontOfSize:15];
        TitleLable.textColor = [UIColor colorWithHexString:@"#333333"];
        TitleLable.textAlignment = NSTextAlignmentCenter;
//        TitleLable.backgroundColor = [UIColor redColor];
        [InfoView addSubview:TitleLable];
    }

    



}
// 更新群聊状态
-(void)changeChatGroupStyleWithStyle:(NSString *)style{
    NSDictionary *dic = @{
                          @"RongGroupId":self.targetId,
                          @"IsFinished":style
                          };
    [SYRequestAPI postDataFromURLScheme:@"rong/RongService.svc/UpdateTutorClassStatus" parameterDictionary:dic success:^(id responseObject) {
        NSDictionary *dic = (NSDictionary *)responseObject;
        if ([dic[@"code"] integerValue] == 10000) {
            if ([style isEqualToString:@"1"]) {
                
                NSDate *date=[NSDate date];
                NSDateFormatter *format3=[[NSDateFormatter alloc] init];
                [format3 setDateFormat:@"MM-dd HH:mm"];
                NSString *time = [format3 stringFromDate:date];
                
                SimpleMessage *videoMessage=[SimpleMessage messageWithContent:time];
                //发送消息
                [self sendMessage:videoMessage pushContent:nil];
                self.chatSessionInputBarControl.hidden = YES;
                self->InfoV.endBtn.backgroundColor = [UIColor whiteColor];
                [self->InfoV.endBtn setTitle:@"已结束" forState:UIControlStateNormal];
                self->InfoV.endBtn.enabled = NO;
                [self->InfoV.endBtn setTitleColor:[UIColor colorWithHexString:@"#20B097"] forState:UIControlStateNormal];
                [self jieSanGroupRequest];
            }
        }
    } fail:^(NSError *error) {
        
    }];
}
// 解散群聊
-(void)jieSanGroupRequest{
    NSDictionary *dic = @{
                          @"RongGroupId":self.targetId,
                          };
    [SYRequestAPI postDataFromURLScheme:@"rong/RongService.svc/DismissRongGroup" parameterDictionary:dic success:^(id responseObject) {
        
    } fail:^(NSError *error) {
        
    }];
}
//功能面板点击事件的方法，通过tag区分点击到的哪个item
- (void)pluginBoardView:(RCPluginBoardView *)pluginBoardView clickedItemWithTag:(NSInteger)tag{
    switch (tag) {
        case 1001:
        {
            // 相册选择图片
            BLImagePickerViewController *imgVc = [[BLImagePickerViewController alloc]init];
            UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:imgVc];
            imgVc.navColor = [UIColor colorWithHexString:@"#20B097"];

            imgVc.view.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
            //获取当前UIWindow 并添加一个视图
            
            UIApplication *ap = [UIApplication sharedApplication];
            
            [ap.keyWindow addSubview:nav.view];

            imgVc.maxNum = 5;
            [imgVc initDataProgress:^(CGFloat progress) {
                
                [nav.view removeFromSuperview];

                
            } finished:^(NSArray<UIImage *> *resultAry, NSArray<PHAsset *> *assetsArry, UIImage *editedImage) {
                for (UIImage *image in resultAry) {
                    RCImageMessage *imgaeMessage = [RCImageMessage messageWithImage:image];
                    [self sendMessage:imgaeMessage pushContent:nil];
                }
                [nav.view removeFromSuperview];

            } cancle:^(NSString *cancleStr) {
                //        DDLOG(@"取消了");
                [nav.view removeFromSuperview];

            }];

            
        }
            break;
        case 1002:{
            //相机拍摄图片
            self.picker = [[UIImagePickerController alloc] init];
            self.picker.delegate = self;
            UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
            self.picker.sourceType = sourceType;
            self.picker.modalPresentationStyle = UIModalPresentationFullScreen;
            
            UIApplication *ap = [UIApplication sharedApplication];
            
            [ap.keyWindow addSubview:self.picker.view];
            
        }
            break;
        case 201:{
            // 发送图片
            SYSendVideoViewController *imagePickerVc = [[SYSendVideoViewController alloc]init];
            imagePickerVc.maxImagesCount = 1 ;
            imagePickerVc.pickerDelegate = self;
            imagePickerVc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
            //            imagePickerVc.view.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height);
            //展示相册中的视频
            imagePickerVc.allowPickingVideo = YES;
            //不展示图片
            imagePickerVc.allowPickingImage = NO;
            //不显示原图选项
            imagePickerVc.allowPickingOriginalPhoto = NO;
            //按时间排序
            imagePickerVc.sortAscendingByModificationDate = YES;

            // 是否自动dismiss
            imagePickerVc.autoDismiss = NO;

            imagePickerVc.allowTakeVideo = NO;


            //            imagePickerVc.cancelBtnClickAndBanck = ^{
            //
            //            };
            [self presentViewController:imagePickerVc animated:YES completion:nil];
            
        }
            break;
        case 202:{
            // 发送文件
            NSArray *documentTypes = @[@"public.content", @"public.text", @"public.source-code ", @"public.image", @"public.audiovisual-content", @"com.adobe.pdf", @"com.apple.keynote.key", @"com.microsoft.word.doc", @"com.microsoft.excel.xls", @"com.microsoft.powerpoint.ppt"];
            UIDocumentPickerViewController *documentPicker = [[UIDocumentPickerViewController alloc] initWithDocumentTypes:documentTypes inMode:UIDocumentPickerModeOpen];
            
            documentPicker.delegate = self;
            
            documentPicker.modalPresentationStyle = UIModalPresentationOverCurrentContext;

            [self presentViewController:documentPicker animated:YES completion:nil];
            
        }
            break;
        case 205:{
            // 录屏
            
            [MBProgressHUD mj_showLoadingInView:self.view];
            [SYRequestAPI bb_TutorServiceImInfoToken:Token success:^(id  _Nonnull dataList) {
                //这里需要房间号，名字，登录账号（生成的）
                [MBProgressHUD mj_hideHUDForView:self.view];
                self->_interactionVC = [[SYBaiBanFuDaoViewController alloc] init];
                //TOP 先写死
//                SaveDataToNSUserDefaults([dataList nilObjectForKey:@"imId"], @"independence_ios");
                self->_interactionVC.userName = [dataList nilObjectForKey:@"imId"];
                self->_interactionVC.userSig = [dataList nilObjectForKey:@"userSig"];
                //NSInteger room = arc4random() %100;

                self->_interactionVC.isChat = YES;
                NSString *roomId = [NSString stringWithFormat:@"8%@",GetDataFromNSUserDefaults(AcountIDDefalut)];

                self->_interactionVC.roomId = roomId;//SJStringWithFormat(room);
                self->_interactionVC.modalPresentationStyle = UIModalPresentationOverFullScreen;
                [self presentViewController:self->_interactionVC animated:YES completion:nil];
                
            } fail:^(NSError *error) {
                [MBProgressHUD mj_hideHUDForView:self.view];
                [MBProgressHUD zr_showError:error.domain];
                //            YLSLog(@"----请求错误");
            }];
            
            
        }
            break;
        case 204:{
            // 拍摄小视频
            
            XFCameraController *cameraController = [XFCameraController defaultCameraController];
            cameraController.isSupport_horizontal_screen = NO;
            __weak XFCameraController *weakCameraController = cameraController;
            
            cameraController.takePhotosCompletionBlock = ^(UIImage *image, NSError *error) {
                NSLog(@"takePhotosCompletionBlock");
                
                [weakCameraController dismissViewControllerAnimated:YES completion:nil];
            };
            
            cameraController.shootCompletionBlock = ^(NSURL *videoUrl, CGFloat videoTimeLength, UIImage *thumbnailImage, NSError *error) {
                NSLog(@"shootCompletionBlock");
                
                [weakCameraController dismissViewControllerAnimated:YES completion:nil];

                __weak typeof(self) WeakSelf = self;
                NSInteger chatType = 1;
                if ([WeakSelf.IsFrom isEqualToString:@"1"]) {
                    chatType = 3;
                }
                RCSightMessage *sightMessage = [RCSightMessage messageWithLocalPath:videoUrl.path thumbnail:thumbnailImage duration:videoTimeLength];
                NSTimeInterval interval = [[NSDate date] timeIntervalSince1970];
                long long totalMilliseconds = interval * 1000;
                NSString *name = [NSString stringWithFormat:@"video_%lld.mp4", totalMilliseconds];
                long long size = [[[NSFileManager defaultManager] attributesOfItemAtPath:videoUrl.path error:nil] fileSize];
                [sightMessage setValue:name forKey:@"name"];
                [sightMessage setValue:@(size) forKey:@"size"];
                NSString *pushContent = @"小视频消息";
                
                [[RCIM sharedRCIM]sendMediaMessage:chatType targetId:self.targetId content:sightMessage pushContent:pushContent pushData:nil progress:^(int progress, long messageId) {
                    
                    
                } success:^(long messageId) {
                    
                    
                    NSLog(@"---------------发送成功");
                    
                } error:^(RCErrorCode errorCode, long messageId) {
                    
                    
                } cancel:^(long messageId) {
                    
                    
                }];
                
                
            };
            cameraController.modalPresentationStyle = UIModalPresentationOverCurrentContext;

            [self presentViewController:cameraController animated:YES completion:nil];

            
        }
            break;
        case 206:{
            // 发送资源
            ResourceViewController *imagePickerVc = [[ResourceViewController alloc]init];
            imagePickerVc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
            imagePickerVc.IsFrom = @"fenxiang";
//            imagePickerVc.isChar = YES;
            imagePickerVc.hasChooseZiYuanMoDel = ^(SYCollectionModel * _Nonnull model) {
//                NSString *urlStr =  [model.path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//                NSURL *url = [NSURL URLWithString:urlStr];
//                RCFileMessage *fileMsg = [RCFileMessage messageWithFile:[url path]];
                if ([model.type isEqualToString:@"4"]) {
                    WMPPTMessage *videoMessage=[WMPPTMessage messageWithContent:model.path];
                    videoMessage.extra = model.titleName;
                    //发送消息
                    [self sendMessage:videoMessage pushContent:nil];
                }else if ([model.type isEqualToString:@"6"]){
                    
                    WMWordMessage *videoMessage=[WMWordMessage messageWithContent:model.path];
                    videoMessage.extra = model.titleName;
                    //发送消息
                    [self sendMessage:videoMessage pushContent:nil];
                    
                }else if ([model.type isEqualToString:@"7"]){
                    
                    WMExcelMessage *videoMessage=[WMExcelMessage messageWithContent:model.path];
                    videoMessage.extra = model.titleName;
                    //发送消息
                    [self sendMessage:videoMessage pushContent:nil];
                }else if ([model.type isEqualToString:@"8"]){
                    
                    WMImageMessage *videoMessage=[WMImageMessage messageWithContent:model.path];
                    
                    videoMessage.extra = model.titleName;
                    //发送消息
                    [self sendMessage:videoMessage pushContent:nil];
                    
                }else if ([model.type isEqualToString:@"9"]){
                    
                    WMHttpMessage *videoMessage=[WMHttpMessage messageWithContent:model.path];
                    
                    videoMessage.extra = model.titleName;
                    //发送消息
                    [self sendMessage:videoMessage pushContent:nil];
                }
                else{
                    WMVideoMessage *videoMessage=[WMVideoMessage messageWithContent:model.path];
                    //发送消息
                    [self sendMessage:videoMessage pushContent:nil];
                }

            };
            [self presentViewController:imagePickerVc animated:YES completion:nil];
        }
            break;
        default:
            break;
    }
    self.modalPresentationStyle = UIModalPresentationOverFullScreen;
}
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    
    
    [self.picker.view removeFromSuperview];

}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info{
         //通过UIImagePickerControllerMediaType判断返回的是照片还是视频
        NSString* type = [info objectForKey:UIImagePickerControllerMediaType];
        //如果返回的type等于kUTTypeImage，代表返回的是照片,并且需要判断当前相机使用的sourcetype是拍照还是相册
        if ([type isEqualToString:(NSString*)kUTTypeImage]&&picker.sourceType==UIImagePickerControllerSourceTypeCamera) {
                //获取照片的原图
            UIImage* original = [info
                                       objectForKey:UIImagePickerControllerOriginalImage];
            // 发送图片信息
            RCImageMessage *imgaeMessage = [RCImageMessage messageWithImage:original];
            [self sendMessage:imgaeMessage pushContent:nil];
                 //如果是拍照的照片，则需要手动保存到本地，系统不会自动保存拍照成功后的照片
            UIImageWriteToSavedPhotosAlbum(original, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
             }
    [self.picker.view removeFromSuperview];

}
//3、保存照片成功后的回调
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error
  contextInfo:(void *)contextInfo{
    
    
}
- (RCMessageBaseCell *)rcConversationCollectionView:(UICollectionView *)collectionView
                             cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    RCMessageModel *model =
    [self.conversationDataRepository objectAtIndex:indexPath.row];
    
    if (!self.displayUserNameInCell) {
        if (model.messageDirection == MessageDirection_RECEIVE) {
            model.isDisplayNickname = NO;
        }
    }
    RCMessageContent *messageContent = model.content;
    
    if ([messageContent isMemberOfClass:[SimpleMessage class]])
    {
        SimpleMessage *message = (SimpleMessage *)messageContent;
        if ([message.extra isEqualToString:@"1"]) {
            __weak typeof(self) weakSelf = self;
            RYChatVideoCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"RYChatVideoCell" forIndexPath:indexPath];
            cell.lookInfoBtnClick = ^{
                
                SYZXFDFuDaoDetailsView *detailsView = [[NSBundle mainBundle] loadNibNamed:@"SYZXFDFuDaoDetailsView" owner:nil options:nil].firstObject;
                [detailsView requestDataClassId:weakSelf.classId];
                [weakSelf.view addSubview:detailsView];
                [detailsView mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.left.equalTo(@0);
                    make.right.equalTo(@0);
                    make.top.equalTo(@0);
                    make.bottom.equalTo(@0);
                }];
                
            };
            [cell setDataModel:model];
            [cell setDelegate:self];
            return cell;
        }
        SimpleMessageCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"SimpleMessageCell" forIndexPath:indexPath];
        __weak typeof(self) weakSelf = self;

        cell.lookInfoBtnClick = ^{
            
            SYZXFDFuDaoDetailsView *detailsView = [[NSBundle mainBundle] loadNibNamed:@"SYZXFDFuDaoDetailsView" owner:nil options:nil].firstObject;
            [detailsView requestDataClassId:weakSelf.classId];
            [weakSelf.view addSubview:detailsView];
            [detailsView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(@0);
                make.right.equalTo(@0);
                make.top.equalTo(@0);
                make.bottom.equalTo(@0);
            }];
            
        };
        [cell setDataModel:model];
        [cell setDelegate:self];
        return cell;
    }else if ([messageContent isMemberOfClass:[WMVideoMessage class]])
    {
        WMVideoMessageCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"WMVideoMessageCell" forIndexPath:indexPath];
        [cell setDataModel:model];
        [cell setDelegate:self];
        cell.lookVideoBtnClick = ^{
            WMVideoMessage *fileMessage = (WMVideoMessage *)model.content;
            
            NSString *imageStr = fileMessage.content;
            
            if (imageStr == nil) {
                
                [MBProgressHUD zr_showError:@"文件出错"];
                return;
            }
            [self requestaPathUrlTask:imageStr];
            
        };
        return cell;
    }else if ([messageContent isMemberOfClass:[WMPPTMessage class]]){
        
        WMPPTMessageCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"WMPPTMessageCell" forIndexPath:indexPath];
        [cell setDataModel:model];
        [cell setDelegate:self];
        cell.lookVideoBtnClick = ^{
            WMPPTMessage *fileMessage = (WMPPTMessage *)model.content;
            
            NSString *imageStr = fileMessage.content;
            if (imageStr == nil) {
                
                [MBProgressHUD zr_showError:@"文件出错"];
                return;
            }
            SYPPTViewController *VC = [[SYPPTViewController alloc]init];
            VC.urlStr = imageStr;
            VC.modalPresentationStyle = UIModalPresentationOverFullScreen;
            [self presentViewController:VC animated:YES completion:nil];

            
        };
        return cell;

    }else if ([messageContent isMemberOfClass:[WMWordMessage class]]){
            
            WMWordMessageCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"WMWordMessageCell" forIndexPath:indexPath];
            [cell setDataModel:model];
            [cell setDelegate:self];
            cell.lookVideoBtnClick = ^{
                WMWordMessage *fileMessage = (WMWordMessage *)model.content;

                NSString *imageStr = fileMessage.content;
                if (imageStr == nil) {
                    
                    [MBProgressHUD zr_showError:@"文件出错"];
                    return;
                }
                SYPPTViewController *VC = [[SYPPTViewController alloc]init];
                VC.urlStr = imageStr;
                VC.modalPresentationStyle = UIModalPresentationOverFullScreen;
                [self presentViewController:VC animated:YES completion:nil];
                
            };
            return cell;
        
        }else if ([messageContent isMemberOfClass:[WMExcelMessage class]]){
            
            WMExcelMessageCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"WMExcelMessageCell" forIndexPath:indexPath];
            [cell setDataModel:model];
            [cell setDelegate:self];
            cell.lookVideoBtnClick = ^{
                WMExcelMessage *fileMessage = (WMExcelMessage *)model.content;

                NSString *imageStr = fileMessage.content;
                if (imageStr == nil) {
                    
                    [MBProgressHUD zr_showError:@"文件出错"];
                    return;
                }
                SYPPTViewController *VC = [[SYPPTViewController alloc]init];
                VC.urlStr = imageStr;
                VC.modalPresentationStyle = UIModalPresentationOverFullScreen;
                [self presentViewController:VC animated:YES completion:nil];
                
            };
            
            return cell;
        }else if ([messageContent isMemberOfClass:[WMImageMessage class]]){
            
            WMImageMessageCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"WMImageMessageCell" forIndexPath:indexPath];
            [cell setDataModel:model];
            [cell setDelegate:self];
            cell.lookVideoBtnClick = ^{
                WMImageMessage *fileMessage = (WMImageMessage *)model.content;
                
                NSString *imageStr = fileMessage.content;
                
                if (imageStr == nil) {
                    
                    [MBProgressHUD zr_showError:@"文件出错"];
                    return;
                }
                imageStr = [imageStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//                [self requestaPathUrlTask:imageStr];
                NSArray *ImageArr = @[imageStr];
               WMPhotoBrowser *Imagebrowser = [WMPhotoBrowser new];
                Imagebrowser.dataSource = (NSMutableArray *)ImageArr;
                Imagebrowser.downLoadNeeded = YES;
                Imagebrowser.modalPresentationStyle = UIModalPresentationOverFullScreen;
                [self presentViewController:Imagebrowser animated:YES completion:nil];
                
                
            };
            return cell;
        }else if ([messageContent isMemberOfClass:[WMHttpMessage class]]){
            
            WMHttpMessageCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"WMHttpMessageCell" forIndexPath:indexPath];
            
            [cell setDataModel:model];
            [cell setDelegate:self];
            cell.lookVideoBtnClick = ^{
                WMHttpMessage *fileMessage = (WMHttpMessage *)model.content;

                NSString *imageStr = fileMessage.content;
                if (imageStr == nil) {
                    
                    [MBProgressHUD zr_showError:@"文件出错"];
                    return;
                }
                SYPPTViewController *VC = [[SYPPTViewController alloc]init];
                VC.urlStr = imageStr;
                VC.modalPresentationStyle = UIModalPresentationOverFullScreen;
                [self presentViewController:VC animated:YES completion:nil];
                
            };
            return cell;
        }

    else {
        return [super rcConversationCollectionView:collectionView cellForItemAtIndexPath:indexPath];

    }
}

- (void)requestaPathUrlTask:(NSString *)taskid {
    if ([taskid containsString:@"http"]) {
        SYPlayerViewController *playerVC = [[SYPlayerViewController alloc] init];
        playerVC.modalPresentationStyle = UIModalPresentationOverFullScreen;
        
        playerVC.urlStr = taskid;
        [self presentViewController:playerVC animated:YES completion:nil];
    } else {
        [MBProgressHUD mj_showLoading];
        [SYRequestAPI bb_TutorVideoUrlByTaskId:taskid success:^(NSString * _Nonnull pathUrl) {
            [MBProgressHUD mj_hideHUD];
            SYPlayerViewController *playerVC = [[SYPlayerViewController alloc] init];
            playerVC.modalPresentationStyle = UIModalPresentationOverFullScreen;
            
            playerVC.urlStr = pathUrl;
            [self presentViewController:playerVC animated:YES completion:nil];
        } fail:^(NSError *error) {
            [MBProgressHUD zr_showError:@"文件出错"];
        }];
    }
}



// 点击消息的方法回调 图片
- (void)presentImagePreviewController:(RCMessageModel *)model{
    


}
-(void)backToFirstVC:(UIButton *)sender{
    [browser.view removeFromSuperview];
    [leftBtn removeFromSuperview];
}
//消息文件
- (void)presentFilePreviewViewController:(RCMessageModel *)model{
    
    
    SYPPTViewController *wordVC = [[SYPPTViewController alloc] init];
    RCFileMessage *fileMessage = (RCFileMessage *)model.content;
    RCMediaMessageContent *mediaMessage = (RCMediaMessageContent *)fileMessage;
    
    wordVC.urlStr = mediaMessage.remoteUrl;
    
    wordVC.modalPresentationStyle = UIModalPresentationOverFullScreen;
    [self presentViewController:wordVC animated:YES completion:nil];
    
}

- (void)didTapMessageCell:(RCMessageModel *)model{
    
    if ([model.content isMemberOfClass:[RCSightMessage class]]) {
        RCSightMessage *message = (RCSightMessage *)model.content;
        SYPlayerViewController *playerVC = [[SYPlayerViewController alloc] init];
        playerVC.modalPresentationStyle = UIModalPresentationOverFullScreen;
        //        NSURL *sourceMovieURL = [NSURL fileURLWithPath:[]];
        NSString *videoStr;
        NSString *pathStr = message.localPath;
        if (pathStr.length > 0) {
//            NSURL *sourceMovieURL = [NSURL fileURLWithPath:pathStr];
            videoStr = pathStr;
            playerVC.isPlayer = YES;
        } else {
            videoStr = message.remoteUrl;
        }
        
        
        
        if (videoStr == nil) {
            
            [MBProgressHUD zr_showError:@"文件出错"];
            return;
        }
        playerVC.urlStr = videoStr;
        [self presentViewController:playerVC animated:YES completion:nil];
        
    }else if ([model.content isMemberOfClass:[RCImageMessage class]]){
        
        RCImageMessage *imageMessage = (RCImageMessage *)model.content;
        NSString *imageStr = imageMessage.remoteUrl;
        if (imageStr == nil) {
            
            [MBProgressHUD zr_showError:@"文件出错"];
            return;
        }

        NSMutableArray *imageArr = [NSMutableArray array];
        [imageArr addObject:imageStr];
        browser = [WMPhotoBrowser new];
        browser.dataSource = imageArr;
        browser.downLoadNeeded = YES;
        leftBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 60, 60)];
        [leftBtn setImage:[UIImage imageNamed:@"back_color"] forState:UIControlStateNormal];
        
        [leftBtn addTarget:self action:@selector(backToFirstVC:) forControlEvents:UIControlEventTouchUpInside];
        
        UIApplication *ap = [UIApplication sharedApplication];
        
        [ap.keyWindow addSubview:browser.view];
        [ap.keyWindow addSubview:leftBtn];
    }else if ([model.content isKindOfClass:[RCFileMessage class]]){
        RCFileMessage *fileMessage = (RCFileMessage *)model.content;

        NSString *imageStr = fileMessage.remoteUrl;

        if (imageStr == nil) {
            
            [MBProgressHUD zr_showError:@"文件出错"];
            return;
        }
        SYPPTViewController *wordVC = [[SYPPTViewController alloc] init];
        RCMediaMessageContent *mediaMessage = (RCMediaMessageContent *)fileMessage;
        
        wordVC.urlStr = mediaMessage.remoteUrl;
        
        wordVC.modalPresentationStyle = UIModalPresentationOverFullScreen;
        [self presentViewController:wordVC animated:YES completion:nil];
    }
    else if ([model.content isKindOfClass:[WMVideoMessage class]]){
        WMVideoMessage *fileMessage = (WMVideoMessage *)model.content;
        
        NSString *imageStr = fileMessage.content;
        
        if (imageStr == nil) {
            
            [MBProgressHUD zr_showError:@"文件出错"];
            return;
        }
        SYPlayerViewController *playerVC = [[SYPlayerViewController alloc] init];
        playerVC.modalPresentationStyle = UIModalPresentationOverFullScreen;
        
        playerVC.urlStr = fileMessage.content;
        [self presentViewController:playerVC animated:YES completion:nil];
    }else if ([model.content isKindOfClass:[WMWordMessage class]]){
        WMWordMessage *fileMessage = (WMWordMessage *)model.content;
        
        NSString *imageStr = fileMessage.content;
        
        if (imageStr == nil) {
            
            [MBProgressHUD zr_showError:@"文件出错"];
            return;
        }
//        SYPlayerViewController *playerVC = [[SYPlayerViewController alloc] init];
//        playerVC.modalPresentationStyle = UIModalPresentationOverFullScreen;
//
//        playerVC.urlStr = fileMessage.content;
//        [self presentViewController:playerVC animated:YES completion:nil];
    }else if ([model.content isKindOfClass:[WMHttpMessageCell class]]){
            WMHttpMessage *fileMessage = (WMHttpMessage *)model.content;
            
            NSString *imageStr = fileMessage.content;
            
            if (imageStr == nil) {
                
                [MBProgressHUD zr_showError:@"文件出错"];
                return;
            }
    //        SYPlayerViewController *playerVC = [[SYPlayerViewController alloc] init];
    //        playerVC.modalPresentationStyle = UIModalPresentationOverFullScreen;
    //
    //        playerVC.urlStr = fileMessage.content;
    //        [self presentViewController:playerVC animated:YES completion:nil];
        }else{
        
        [super didTapMessageCell:model];
    }
    
    
}
//
- (CGSize)rcConversationCollectionView:(UICollectionView *)collectionView
                                layout:(UICollectionViewLayout *)collectionViewLayout
                sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    RCMessageModel *model = [self.conversationDataRepository objectAtIndex:indexPath.row];
    RCMessageContent *messageContent = model.content;
    if ([messageContent isMemberOfClass:[RCRealTimeLocationStartMessage class]]) {
        if (model.isDisplayMessageTime) {
            return CGSizeMake(collectionView.frame.size.width, 66);
        }
        return CGSizeMake(collectionView.frame.size.width, 66);
    }   else if ([messageContent isMemberOfClass:[SimpleMessage class]])
    {
        return CGSizeMake(collectionView.frame.size.width, 80);
    } else if ([messageContent isMemberOfClass:[WMVideoMessage class]])
    {
        return CGSizeMake(collectionView.frame.size.width, 140);
    } else if ([messageContent isMemberOfClass:[WMPPTMessage class]])
       {
           return CGSizeMake(collectionView.frame.size.width, 140);
           
       }
    else if ([messageContent isMemberOfClass:[WMWordMessage class]])
    {
        return CGSizeMake(collectionView.frame.size.width, 140);
        
    }    else if ([messageContent isMemberOfClass:[WMExcelMessage class]])
    {
        return CGSizeMake(collectionView.frame.size.width, 140);
        
    }    else if ([messageContent isMemberOfClass:[WMExcelMessage class]])
    {
        return CGSizeMake(collectionView.frame.size.width, 140);
        
    } else if ([messageContent isMemberOfClass:[WMHttpMessage class]])
       {
           return CGSizeMake(collectionView.frame.size.width, 140);
       }
    else {
        return [super rcConversationCollectionView:collectionView layout:collectionViewLayout sizeForItemAtIndexPath:indexPath];
//        return CGSizeMake(300, 60);

    }
}
// 图片发送成功的回调
- (void)didSendMessage:(NSInteger)status content:(RCMessageContent *)messageContent{
    if (status == 0) {
        NSLog(@"发送成功");
    }else{
        NSLog(@"发送失败");

    }
}
#pragma mark -----------------------------UIDocumentPickerDelegate
- (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url {
    
    BOOL fileUrlAuthozied = [url startAccessingSecurityScopedResource];
    if(fileUrlAuthozied){
        NSFileCoordinator *fileCoordinator = [[NSFileCoordinator alloc] init];
        NSError *error;
        __block NSData *fileData;
        [fileCoordinator coordinateReadingItemAtURL:url options:0 error:&error byAccessor:^(NSURL *newURL) {
            
            NSString *fileName = [newURL lastPathComponent];
            
            NSString *fileStr = [NSString stringWithContentsOfURL:newURL encoding:NSUTF8StringEncoding error:nil];
            
            
            self.modalPresentationStyle = UIModalPresentationOverFullScreen;
            
            RCFileMessage *fileMsg = [RCFileMessage messageWithFile:[newURL path]];
            [self sendMessage:fileMsg pushContent:nil];
            
        }];
        [url stopAccessingSecurityScopedResource];
        
    }else{
        //Error handling
        
    }
}
- (void)documentPickerWasCancelled:(UIDocumentPickerViewController *)controller{
    
    self.modalPresentationStyle = UIModalPresentationOverFullScreen;
}



- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingVideo:(UIImage *)coverImage sourceAssets:(PHAsset *)asset{
    
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    NSInteger chatType = 1;
    if ([self.IsFrom isEqualToString:@"1"]) {
        chatType = 3;
    }
    //iOS8以后返回PHAsset
    PHAsset *phAsset = asset;
    
    if (phAsset.mediaType == PHAssetMediaTypeVideo) {
        //从PHAsset获取相册中视频的url
        __weak typeof(self) weakSelf = self;

        PHVideoRequestOptions *options = [[PHVideoRequestOptions alloc] init];
        options.version = PHImageRequestOptionsVersionCurrent;
        options.deliveryMode = PHVideoRequestOptionsDeliveryModeAutomatic;
        PHImageManager *manager = [PHImageManager defaultManager];
        [manager requestAVAssetForVideo:phAsset options:options resultHandler:^(AVAsset * _Nullable asset, AVAudioMix * _Nullable audioMix, NSDictionary * _Nullable info) {
            AVURLAsset *urlAsset = (AVURLAsset *)asset;
            NSURL *url = urlAsset.URL;
            NSUInteger second = 0;
            second = urlAsset.duration.value / urlAsset.duration.timescale;

            RCSightMessage *sightMessage = [RCSightMessage messageWithLocalPath:url.path thumbnail:coverImage duration:second];
            NSTimeInterval interval = [[NSDate date] timeIntervalSince1970];
            long long totalMilliseconds = interval * 1000;
            NSString *name = [NSString stringWithFormat:@"video_%lld.mp4", totalMilliseconds];
            long long size = [[[NSFileManager defaultManager] attributesOfItemAtPath:url.path error:nil] fileSize];
            [sightMessage setValue:name forKey:@"name"];
            [sightMessage setValue:@(size) forKey:@"size"];
            NSString *pushContent = @"小视频消息";

            [[RCIM sharedRCIM]sendMediaMessage:chatType targetId:self.targetId content:sightMessage pushContent:pushContent pushData:nil progress:^(int progress, long messageId) {


            } success:^(long messageId) {


                NSLog(@"---------------发送成功");

            } error:^(RCErrorCode errorCode, long messageId) {


            } cancel:^(long messageId) {


            }];
        }];
    }
    
//    WMVideoMessage *videoMessage=[WMVideoMessage messageWithContent:@"https://1256468886.vod2.myqcloud.com/840e6e58vodcq1256468886/227b6a015285890794707389863/zjMmbBYqJ4sA.mov"];
//    //发送消息
//    [self sendMessage:videoMessage pushContent:nil];
}

- (void)faSongLuPing:(NSNotification *)info{
    NSString *pathFiel = [info.userInfo objectForKey:@"path"];
    WMVideoMessage *videoMessage=[WMVideoMessage messageWithContent:pathFiel];
    //发送消息
    [self sendMessage:videoMessage pushContent:nil];
    
}
/*
 因为我们要根据视频资源AVURLAsset重新构建新实例，构建结果为AVMutableComposition实例，而需要修正角度的应该是AVMutableComposition实例，而不是之前的AVURLAsset实例。AVMutableComposition实例的角度应该是AVURLAsset的角度
 */
//- (void)startExportMP4VideoWithVideoAsset:(AVURLAsset *)videoAsset presetName:(NSString *)presetName success:(void (^)(NSString *outputPath))success failure:(void (^)(NSString *errorMessage, NSError *error))failure {
//    AVMutableComposition *composition = [AVMutableComposition composition];
//    
//    AVMutableCompositionTrack *compositionVideoTrack = [composition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid];
//    AVMutableCompositionTrack *compositionAudioTrack = [composition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
//    
//    AVAssetTrack *sourceVideoTrack = [videoAsset tracksWithMediaType:AVMediaTypeVideo].firstObject;
//    AVAssetTrack *sourceAudioTrack = [videoAsset tracksWithMediaType:AVMediaTypeAudio].firstObject;
//    
//    [compositionVideoTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, videoAsset.duration) ofTrack:sourceVideoTrack atTime:kCMTimeZero error:nil];
//    [compositionAudioTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, videoAsset.duration) ofTrack:sourceAudioTrack atTime:kCMTimeZero error:nil];
//    
//    
//    NSArray *presets = [AVAssetExportSession exportPresetsCompatibleWithAsset:composition];
//    
//    if ([presets containsObject:presetName]) {
//        AVAssetExportSession *session = [[AVAssetExportSession alloc] initWithAsset:composition presetName:presetName];
//        // 输出地址
//        NSDateFormatter *formater = [[NSDateFormatter alloc] init];
//        [formater setDateFormat:@"yyyy-MM-dd-HH:mm:ss-SSS"];
//        NSString *outputPath = [NSHomeDirectory() stringByAppendingFormat:@"/tmp/video-%@.mp4", [formater stringFromDate:[NSDate date]]];
//        session.outputURL = [NSURL fileURLWithPath:outputPath];
//        // 优化
//        session.shouldOptimizeForNetworkUse = YES;
//        
//        NSArray *supportedTypeArray = session.supportedFileTypes;
//        if ([supportedTypeArray containsObject:AVFileTypeMPEG4]) {
//            session.outputFileType = AVFileTypeMPEG4;
//        } else if (supportedTypeArray.count == 0) {
//            if (failure) {
//                failure(@"该视频类型暂不支持导出", nil);
//            }
//            NSLog(@"No supported file types 视频类型暂不支持导出");
//            return;
//        } else {
//            session.outputFileType = [supportedTypeArray objectAtIndex:0];
//        }
//        
//        if (![[NSFileManager defaultManager] fileExistsAtPath:[NSHomeDirectory() stringByAppendingFormat:@"/tmp"]]) {
//            [[NSFileManager defaultManager] createDirectoryAtPath:[NSHomeDirectory() stringByAppendingFormat:@"/tmp"] withIntermediateDirectories:YES attributes:nil error:nil];
//        }
//        
//        AVMutableVideoComposition *videoComposition = [self fixedCompositionWithAsset:composition degrees:[self degressFromVideoFileWithAsset:videoAsset]];
//        if (videoComposition.renderSize.width) {
//            // 修正视频转向
//            session.videoComposition = videoComposition;
//        }
//        
//        // 合成完毕
//        [session exportAsynchronouslyWithCompletionHandler:^{
//            dispatch_async(dispatch_get_main_queue(), ^{
//                switch (session.status) {
//                    case AVAssetExportSessionStatusUnknown: {
//                        NSLog(@"AVAssetExportSessionStatusUnknown");
//                    }  break;
//                    case AVAssetExportSessionStatusWaiting: {
//                        NSLog(@"AVAssetExportSessionStatusWaiting");
//                    }  break;
//                    case AVAssetExportSessionStatusExporting: {
//                        NSLog(@"AVAssetExportSessionStatusExporting");
//                    }  break;
//                    case AVAssetExportSessionStatusCompleted: {
//                        NSLog(@"AVAssetExportSessionStatusCompleted");
//                        if (success) {
//                            success(outputPath);
//                        }
//                    }  break;
//                    case AVAssetExportSessionStatusFailed: {
//                        NSLog(@"AVAssetExportSessionStatusFailed");
//                        if (failure) {
//                            failure(@"视频导出失败", session.error);
//                        }
//                    }  break;
//                    case AVAssetExportSessionStatusCancelled: {
//                        NSLog(@"AVAssetExportSessionStatusCancelled");
//                        if (failure) {
//                            failure(@"导出任务已被取消", nil);
//                        }
//                    }  break;
//                    default: break;
//                }
//            });
//        }];
//    } else {
//        if (failure) {
//            NSString *errorMessage = [NSString stringWithFormat:@"当前设备不支持该预设:%@", presetName];
//            failure(errorMessage, nil);
//        }
//    }
//}
//
//
///// 获取优化后的视频转向信息
//- (AVMutableVideoComposition *)fixedCompositionWithAsset:(AVAsset *)videoAsset degrees:(int)degrees {
//    AVMutableVideoComposition *videoComposition = [AVMutableVideoComposition videoComposition];
//    if (degrees != 0) {
//        CGAffineTransform translateToCenter;
//        CGAffineTransform mixedTransform;
//        videoComposition.frameDuration = CMTimeMake(1, 30);
//        
//        NSArray *tracks = [videoAsset tracksWithMediaType:AVMediaTypeVideo];
//        AVAssetTrack *videoTrack = [tracks objectAtIndex:0];
//        
//        AVMutableVideoCompositionInstruction *roateInstruction = [AVMutableVideoCompositionInstruction videoCompositionInstruction];
//        roateInstruction.timeRange = CMTimeRangeMake(kCMTimeZero, [videoAsset duration]);
//        AVMutableVideoCompositionLayerInstruction *roateLayerInstruction = [AVMutableVideoCompositionLayerInstruction videoCompositionLayerInstructionWithAssetTrack:videoTrack];
//        
//        if (degrees == 90) {
//            // 顺时针旋转90°
//            translateToCenter = CGAffineTransformMakeTranslation(videoTrack.naturalSize.height, 0.0);
//            mixedTransform = CGAffineTransformRotate(translateToCenter,M_PI_2);
//            videoComposition.renderSize = CGSizeMake(videoTrack.naturalSize.height,videoTrack.naturalSize.width);
//            [roateLayerInstruction setTransform:mixedTransform atTime:kCMTimeZero];
//        } else if(degrees == 180){
//            // 顺时针旋转180°
//            translateToCenter = CGAffineTransformMakeTranslation(videoTrack.naturalSize.width, videoTrack.naturalSize.height);
//            mixedTransform = CGAffineTransformRotate(translateToCenter,M_PI);
//            videoComposition.renderSize = CGSizeMake(videoTrack.naturalSize.width,videoTrack.naturalSize.height);
//            [roateLayerInstruction setTransform:mixedTransform atTime:kCMTimeZero];
//        } else if(degrees == 270){
//            // 顺时针旋转270°
//            translateToCenter = CGAffineTransformMakeTranslation(0.0, videoTrack.naturalSize.width);
//            mixedTransform = CGAffineTransformRotate(translateToCenter,M_PI_2*3.0);
//            videoComposition.renderSize = CGSizeMake(videoTrack.naturalSize.height,videoTrack.naturalSize.width);
//            [roateLayerInstruction setTransform:mixedTransform atTime:kCMTimeZero];
//        }
//        
//        roateInstruction.layerInstructions = @[roateLayerInstruction];
//        // 加入视频方向信息
//        videoComposition.instructions = @[roateInstruction];
//    }
//    return videoComposition;
//}
//
///// 获取视频角度
//- (int)degressFromVideoFileWithAsset:(AVAsset *)asset {
//    int degress = 0;
//    NSArray *tracks = [asset tracksWithMediaType:AVMediaTypeVideo];
//    if([tracks count] > 0) {
//        AVAssetTrack *videoTrack = [tracks objectAtIndex:0];
//        CGAffineTransform t = videoTrack.preferredTransform;
//        if(t.a == 0 && t.b == 1.0 && t.c == -1.0 && t.d == 0){
//            // Portrait
//            degress = 90;
//        } else if(t.a == 0 && t.b == -1.0 && t.c == 1.0 && t.d == 0){
//            // PortraitUpsideDown
//            degress = 270;
//        } else if(t.a == 1.0 && t.b == 0 && t.c == 0 && t.d == 1.0){
//            // LandscapeRight
//            degress = 0;
//        } else if(t.a == -1.0 && t.b == 0 && t.c == 0 && t.d == -1.0){
//            // LandscapeLeft
//            degress = 180;
//        }
//    }
//    return degress;
//}


// 从详情页面过来时候返回按钮的点击
-(void)detailInfoVcBackClick{
    
    if (self.detailVCBack) {
        self.detailVCBack();
    }
}
@end
